//
//  MyFMTableViewController.m
//  MoeFM
//
//  Created by miyang on 14-11-5.
//  Copyright (c) 2014年 StraightJet. All rights reserved.
//

#import "MyFMTableViewController.h"




@interface MyFMTableViewController ()<UIAlertViewDelegate,UIActionSheetDelegate>

@property (nonatomic,strong)NSUserDefaults *userDate;

@end

@implementation MyFMTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        _dateDic = [[NSDictionary alloc] init];
        _userDate = [NSUserDefaults standardUserDefaults];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
    
    //headView.backgroundColor = [UIColor greenColor];
    
    
    UIImageView *userImg = [[UIImageView alloc] initWithFrame:CGRectMake(110, 20, 100, 100)];
    [userImg setImage:[UIImage imageNamed:@"user_128.png"]];
    userImg.layer.masksToBounds = YES;
    userImg.layer.cornerRadius = 50;
    userImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(login)];
    [userImg addGestureRecognizer:tap];
    self.userImg = userImg;
    [headView addSubview:userImg];

    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 140, 320, 20)];
    nameLabel.text = @"未登录";
    nameLabel.font = [UIFont systemFontOfSize:20];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel = nameLabel;
    [headView addSubview:nameLabel];
    
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 179.5, 320, 0.5)];
    line.backgroundColor = [UIColor grayColor];
    [headView addSubview:line];
  
    
    self.tableView.tableHeaderView = headView;
    

    
    
    UIButton *lognOutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lognOutBtn.frame = CGRectMake(60, 20, 200, 40);
    lognOutBtn.backgroundColor = [UIColor grayColor];
    [lognOutBtn setTitle:@"注销账户" forState:UIControlStateNormal];
    [lognOutBtn addTarget:self action:@selector(logOut) forControlEvents:UIControlEventTouchUpInside];
    self.lognOutBtn = lognOutBtn;
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    [footView addSubview:lognOutBtn];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 0.5)];
    line1.backgroundColor = [UIColor grayColor];
    [footView addSubview:line1];
    
    self.tableView.tableFooterView = footView;
    
    
    if ([FavManager sharedManager].status == UserStatusLogIn) {
        userImg.userInteractionEnabled = NO;
        _nameLabel.text = [FavManager sharedManager].userdetail.user_nickname;
        NSString *imgstr = [[FavManager sharedManager].userdetail.user_avatar objectForKey:@"medium"];
        [_userImg setImageWithURL:[NSURL URLWithString:imgstr]];
        lognOutBtn.backgroundColor = [UIColor greenColor];
    }
    
    
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myfm"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myfm"];
    }
    
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"我的收藏";
            break;
        case 1:
            cell.textLabel.text = @"定时关闭";
            break;
        case 2:
            cell.textLabel.text = @"关于";
            break;
        default:
            break;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSelector:@selector(deselect) withObject:nil afterDelay:0.2f];
    switch (indexPath.row) {
        case 0:
        {
            _collection = [[CollectionTableViewController alloc] init];
            _collection.radioarr = [FavManager sharedManager].radioarr;
            _collection.musicarr = [FavManager sharedManager].musicarr;
            _collection.songarr = [FavManager sharedManager].songarr;
            [self.navigationController pushViewController:_collection animated: YES];
        }
            break;
        case 1:
        {
            if ([_countDownTimer isValid]) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"定时已启动" message:[NSString stringWithFormat:@"剩余时间%d分%d秒",(_secondsCountDown / 60),(_secondsCountDown % 60) ] delegate:self cancelButtonTitle:@"关闭定时" otherButtonTitles:@"返回", nil];
                [alertView show];
                
            } else {
                
                UIActionSheet *acitonSheet = [[UIActionSheet alloc] initWithTitle:@"定时关闭" delegate:self cancelButtonTitle:@"返回" destructiveButtonTitle:nil otherButtonTitles:@"15分钟",@"30分钟",@"45分钟", nil];
                
                
                [acitonSheet showInView:[UIApplication sharedApplication].keyWindow];
            }
                   
            
            
            
        }
            break;
        case 2:
        {
            AboutViewController *about = [[AboutViewController alloc] init];
            [self.navigationController pushViewController:about animated:YES];
        }
            break;
            
        default:
            break;
    }
    
}



- (void)login
{
    webViewController *loginWebViewController = [[webViewController alloc] init];
    
    [self presentViewController:loginWebViewController
                       animated:YES
                     completion:^{
                         [self.oauth1Controller loginWithWebView:loginWebViewController.webView completion:^(NSDictionary *oauthTokens, NSError *error) {
                             if (!error) {
                                 // Store your tokens for authenticating your later requests, consider storing the tokens in the Keychain
                                 self.oauthToken = oauthTokens[@"oauth_token"];
                                 self.oauthTokenSecret = oauthTokens[@"oauth_token_secret"];
                                 [_userDate setObject:_oauthToken forKey:@"oauthToken"];
                                 [_userDate setObject:_oauthTokenSecret forKey:@"oauthTokenSecret"];
                                 [_userDate synchronize];
                                 [FavManager sharedManager].status = UserStatusLogIn;
                                 
                                 [FavManager sharedManager].oauthToken = _oauthToken;
                                 [FavManager sharedManager].oauthTokenSecret = _oauthTokenSecret;
                                 
                                 [[FavManager sharedManager] getFavsWiki];
                                 [[FavManager sharedManager] getFavsSub];
                                 
                                 _lognOutBtn.backgroundColor = [UIColor greenColor];
                                 
                                 [self request:@"http://api.moefou.org/user/detail.json" andParameters:nil];
                                 __weak UILabel *blockLabel = _nameLabel;
                                 __weak UIImageView *blockImg = _userImg;
                                 
                                 _dicBlock = ^(NSDictionary *dateDic) {
                                     NSDictionary *userDic = [dateDic objectForKey:@"user"];
                                     blockLabel.text = [userDic objectForKey:@"user_nickname"];
                                     NSDictionary *userAvatar = [userDic objectForKey:@"user_avatar"];
                                     NSURL *userImg = [NSURL URLWithString:[userAvatar objectForKey:@"medium"]];
                                     [blockImg setImageWithURL:userImg];

                                 };

                                 
                             }
                             else
                             {
                                 NSLog(@"Error authenticating: %@", error.localizedDescription);
                             }
                             [self dismissViewControllerAnimated:YES completion: ^{
                                 self.oauth1Controller = nil;
                             }];
                         }];
                     }];
}

- (void)logOut
{
    if ([FavManager sharedManager].status == UserStatusLogIn) {
        
        NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (NSHTTPCookie *cookie in [storage cookies]) {
            if (cookie.isSecure) {
                [storage deleteCookie:cookie];
            }
        }
        
        // Clear tokens from instance variables
        self.oauthToken = nil;
        self.oauthTokenSecret = nil;
        
        [FavManager sharedManager].oauthToken = nil;
        [FavManager sharedManager].oauthTokenSecret = nil;
        
        
        [_userDate setObject:@"" forKey:@"oauthToken"];
        [_userDate setObject:@"" forKey:@"oauthTokenSecret"];
        [_userDate synchronize];
        [_userImg setImage:[UIImage imageNamed:@"user_128.png"]];
        _nameLabel.text = @"未登录";
        _lognOutBtn.backgroundColor = [UIColor grayColor];
        [FavManager sharedManager].status = UserStatusLogOut;
    }
    
}

- (void)request:(NSString *)path andParameters:(NSDictionary *)parameters
{
    
    NSURLRequest *request = [OAuth1Controller preparedRequestForPath:path
                                                          parameters:parameters
                                                          HTTPmethod:@"GET"
                                                          oauthToken:self.oauthToken
                                                         oauthSecret:self.oauthTokenSecret];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *returndic = [responseObject valueForKey:@"response"];
        _dicBlock(returndic);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        _userImg.userInteractionEnabled = YES;
    }];
    
    
    [[NSOperationQueue mainQueue] addOperation:op];
}

//- (void)network:(NSString *)url
//{
//    AFHTTPRequestOperationManager *music = [AFHTTPRequestOperationManager manager];
//    [music GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSDictionary *dic = [[NSDictionary alloc] init];
//        dic = [responseObject objectForKey:@"response"];
//        NSMutableArray *array = [[NSMutableArray alloc] init];
//        array = [dic objectForKey:@"playlist"];
//        
//        NSMutableArray *namearr = [[NSMutableArray alloc] init];
//        NSMutableArray *urlarr = [[NSMutableArray alloc] init];
//        for (dic in array) {
//            [namearr addObject:[dic objectForKey:@"title"]];
//            [urlarr addObject:[dic objectForKey:@"url"]];
//        }
//        [self.tableView reloadData];
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"error %@",operation);
//    }];
//}

- (OAuth1Controller *)oauth1Controller
{
    if (_oauth1Controller == nil) {
        _oauth1Controller = [[OAuth1Controller alloc] init];
    }
    return _oauth1Controller;
}

- (void)timeSetWithTime:(int)time
{
    NSLog(@"timeset");

    _secondsCountDown = time;
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    
    [_countDownTimer fire];
}

- (void)timeFireMethod
{
    NSLog(@"%d",_secondsCountDown);
    _secondsCountDown--;
    if (_secondsCountDown <= 0) {
        [[PlayerViewController sharPlayer].audioPlayer stop];
        [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        [_countDownTimer invalidate];
        NSLog(@"stop   %d",[_countDownTimer isValid]);
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [_countDownTimer invalidate];
    }
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [self timeSetWithTime:60*15];
            break;
        case 1:
            [self timeSetWithTime:60*30];
            break;
        case 2:
            [self timeSetWithTime:60*45];
            break;
        case 3:
            break;
        default:
            break;
    }
}

- (void)deselect
{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

@end
